package com.ruoyi.canteen.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.canteen.domain.Dish;
import com.ruoyi.canteen.domain.SetmealDish;
import com.ruoyi.canteen.domain.dto.MealListDto;
import com.ruoyi.canteen.domain.vo.MealListVo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.canteen.mapper.SetmealMapper;
import com.ruoyi.canteen.domain.Setmeal;
import com.ruoyi.canteen.service.ISetmealService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 套餐管理Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-28
 */
@Service
public class SetmealServiceImpl implements ISetmealService
{
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 查询套餐管理
     *
     * @param id 套餐管理主键
     * @return 套餐管理
     */
    @Override
    public MealListDto selectSetmealById(Long id)
    {
        MealListDto dto = setmealMapper.selectSetmealById(id);
        String idsStr = dto.getSelectedDishesStr();
        List<Long> ids = Arrays.stream(idsStr.split(","))
                .filter(s -> !s.trim().isEmpty())
                .map(Long::parseLong)
                .collect(Collectors.toList());
        dto.setSelectedDishes(ids);
        return dto;
    }

    /**
     * 查询套餐管理列表
     *
     * @param setmeal 套餐管理
     * @return 套餐管理
     */
    @Override
    public List<MealListDto> selectMealList(MealListDto meal)
    {
        List<MealListDto> dtos = setmealMapper.selectMealList(meal);
        dtos.forEach(dto -> {
            String idsStr = dto.getSelectedDishesStr();
            List<Long> ids = Arrays.stream(idsStr.split(","))
                    .filter(s -> !s.trim().isEmpty())
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            dto.setSelectedDishes(ids);
        });
        return dtos;
    }

    /**
     * 新增套餐管理
     *
     * @param setmeal 套餐管理
     * @return 结果
     */
    @Override
    public int insertSetmeal(MealListDto meal)
    {
        List<Long> dishIds = meal.getSelectedDishes();
        if(CollectionUtils.isEmpty(dishIds)){
            return 0;
        }
        else{
            List<Dish> dishes = setmealMapper.selectDishsById(dishIds);
            StringBuilder descriptionBuilder = new StringBuilder();
            for (Dish dish : dishes) {
                if (Arrays.asList(1L, 2L, 3L).contains(dish.getCategoryId())) {
                    if (descriptionBuilder.length() > 0) {
                        descriptionBuilder.append("+");
                    }
                    descriptionBuilder.append(dish.getName());
                }
            }
            String description = descriptionBuilder.toString();
            Setmeal setmeal = new Setmeal();
            setmeal.setDescription(description);
            setmeal.setIsDeleted(0L);
            setmeal.setStatus(1L);
            setmeal.setCreateUser(SecurityUtils.getUserId());
            setmeal.setUpdateUser(SecurityUtils.getUserId());
            setmeal.setName(meal.getName());
            setmeal.setImage(meal.getImage());
            setmeal.setCreateTime(new Date());
            setmeal.setUpdateTime(new Date());
            if (StringUtils.isBlank(meal.getCode())) {
                String datetime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"));
                // 拼接最终 code
                meal.setCode("S" + datetime);
            }
            setmeal.setCode(meal.getCode());
            setmealMapper.insertSetmeal(setmeal);
            Long mealId = setmeal.getId();
            List<SetmealDish> mealDishes = new ArrayList<>();
            for(Long dishId : dishIds) {
                SetmealDish mealDish = new SetmealDish();
                mealDish.setSetmealId(mealId);
                mealDish.setDishId(dishId);
                mealDish.setCreateUser(SecurityUtils.getUserId());
                mealDish.setUpdateUser(SecurityUtils.getUserId());
                mealDish.setCreateTime(new Date());
                mealDishes.add(mealDish);
                mealDish.setCreateTime(new Date());
                mealDish.setUpdateTime(new Date());
            }
            // 调用批量插入方法
            setmealMapper.batchInsertMealDishes(mealDishes);
        }
        return 3;
    }

    /**
     * 修改套餐管理
     *
     * @param setmeal 套餐管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateSetmeal(MealListDto meal) {
        List<Long> dishIds = meal.getSelectedDishes();
        Long mealId = meal.getId();
        if(!CollectionUtils.isEmpty(dishIds)){
            List<Dish> dishs = setmealMapper.selectDishs(dishIds);
            if (!CollectionUtils.isEmpty(dishs)) {
                String dishNames = dishs.stream()
                        .map(Dish::getName)
                        .collect(Collectors.joining("+"));
                meal.setDescription(dishNames);
            }
        }
        // 1. 更新套餐基本信息
        int result = setmealMapper.updateSetmeal(meal);

        // 2. 删除原有套餐菜品关联
        setmealMapper.deleteBySetmealId(mealId);

        // 3. 插入新的关联数据（如果存在菜品）
        if (dishIds != null && !dishIds.isEmpty()) {
            Long currentUserId = SecurityUtils.getUserId(); // 获取当前用户ID
            LocalDateTime now = LocalDateTime.now();
            List<SetmealDish> setmealDishes = new ArrayList<>();
            for (Long dishId : dishIds) {
                SetmealDish sd = new SetmealDish();
                sd.setSetmealId(mealId);
                sd.setDishId(dishId);
                sd.setCreateTime(new Date());
                sd.setUpdateTime(new Date());
                sd.setCreateUser(currentUserId);
                sd.setUpdateUser(currentUserId);
                setmealDishes.add(sd);
            }
            setmealMapper.batchInsertSetmealDish(setmealDishes);
        }

        return result;
    }

    /**
     * 批量删除套餐管理
     *
     * @param ids 需要删除的套餐管理主键
     * @return 结果
     */
    @Override
    public int deleteSetmealByIds(Long[] ids)
    {
        return setmealMapper.deleteSetmealByIds(ids);
    }

    /**
     * 删除套餐管理信息
     *
     * @param id 套餐管理主键
     * @return 结果
     */
    @Override
    public int deleteSetmealById(Long id)
    {
        return setmealMapper.deleteSetmealById(id);
    }

    @Override
    public List<MealListVo> getDishList() {
        return setmealMapper.getDishList();
    }
}
